import { downloadFile, getUrlWithBlob } from '@/utils/file'
import { ref, unref } from 'vue'
import {
  ImgClip,
  MP4Clip,
  OffscreenSprite,
  renderTxt2ImgBitmap,
  Combinator,
} from '@webav/av-cliper'

// [官网demo](https://bilibili.github.io/WebAV/demo)

export const useVideoWatermark = () => {
  const resBlob = ref()

  /**
   * @description 视频添加水印
   * @param videoSrc 视频文件url
   * @param watermarkText 水印文本，可选
   */
  const videoWatermark = async (videoSrc: string, watermarkText = 'mm system watermark') => {
    const fetchRes = await fetch(videoSrc)
    const clip = new MP4Clip(fetchRes.body!)

    const videoSpr = new OffscreenSprite(clip)
    const watermarkSpr = new OffscreenSprite(
      new ImgClip(
        await renderTxt2ImgBitmap(
          watermarkText,
          `font-size:40px; color: white; text-shadow: 2px 2px 6px red;`,
        ),
      ),
    )
    // watermarkSpr.time = { offset: 0, duration: 5e6 };
    // watermarkSpr.setAnimation(
    //   {
    //     '0%': { x: 0, y: 0 },
    //     '25%': { x: 1200, y: 680 },
    //     '50%': { x: 1200, y: 0 },
    //     '75%': { x: 0, y: 680 },
    //     '100%': { x: 0, y: 0 }
    //   },
    //   { duration: 4e6, iterCount: 1 }
    // );
    // watermarkSpr.zIndex = 10;
    // watermarkSpr.opacity = 0.5;

    const com = new Combinator({
      width: 1280,
      height: 720,
    })

    await com.addSprite(videoSpr, { main: true })
    await com.addSprite(watermarkSpr)

    resBlob.value = await new Response(com?.output()).blob()
  }

  const saveVideo = (fileName: string) => {
    const url = getUrlWithBlob(unref(resBlob))
    downloadFile(url, fileName)
  }

  return {
    videoWatermark,
    saveVideo,
  }
}
